package com.iot.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.iot.commons.ResponseResult;
import com.iot.enums.StatusEnum;
import com.iot.model.dto.*;
import com.iot.model.query.DeviceDataQuery;
import com.iot.model.vo.AuthInfoVo;
import com.iot.service.DeviceDataBpService;
import com.iot.service.DeviceDataService;
import com.iot.service.DeviceDataStepsService;
import com.iot.utils.DateUtil;
import com.iot.utils.ResponseResultUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;


/**
 * DeviceServiceImpl
 *
 * @author: dh
 * @date: 2024-04-20 23:39:54
 */
@Service
@RequiredArgsConstructor
public class DeviceDataServiceImpl implements DeviceDataService {

    private static final String DEVICE_DATA_URL = "https://app.xincore-tech.com/index.php/Home/common/device/list/myself";

    private final DeviceDataBpService deviceDataBpService;

    private final DeviceDataStepsService deviceDataStepsService;

    @Override
    public ResponseResult uploadDeviceData(DeviceDataQuery query) {
        AuthInfoVo authInfoEntity = (AuthInfoVo) StpUtil.getSession().get("loginInfo");
        if (null == authInfoEntity) {
            return ResponseResultUtil.authInfoFailure();
        }
        if (null == query) {
            return ResponseResultUtil.paramFailure();
        }
        String mac = query.getMac();
        String deviceId = query.getDeviceId();
        String version = query.getVersion();
        String bluetooth = query.getBluetooth();

        if (StringUtils.isBlank(mac) || StringUtils.isBlank(deviceId) || StringUtils.isBlank(version) || StringUtils.isBlank(bluetooth)) {
            return ResponseResultUtil.paramFailure();
        }
        List<DeviceDataStepsDto> stepDtoList = Lists.newArrayList();
        List<DeviceDataStepsDto> stepsVersionList = packageStepList(getDeviceData(mac, version, deviceId, bluetooth, "1"));
        List<DeviceDataStepsDto> stepsBluetoothList = packageStepList(getDeviceData(mac, version, bluetooth, deviceId, "1"));

        if (CollectionUtils.isNotEmpty(stepsVersionList)) {
            stepDtoList.addAll(stepsVersionList);
        }
        if (CollectionUtils.isNotEmpty(stepsBluetoothList)) {
            stepDtoList.addAll(stepsBluetoothList);
        }
        deviceDataStepsService.upload(stepDtoList, authInfoEntity.getId());

        List<DeviceDataBpDto> bpDtoList = Lists.newArrayList();
        List<DeviceDataBpDto> bpVersionList = packageBpList(getDeviceData(mac, version,deviceId , bluetooth, "4"));
        List<DeviceDataBpDto> bpBluetoothList = packageBpList(getDeviceData(mac,version, bluetooth,  deviceId, "4"));

        if (CollectionUtils.isNotEmpty(bpVersionList)) {
            bpDtoList.addAll(bpVersionList);
        }
        if (CollectionUtils.isNotEmpty(bpBluetoothList)) {
            bpDtoList.addAll(bpBluetoothList);
        }
        deviceDataBpService.upload(bpDtoList, authInfoEntity.getId());

        return ResponseResultUtil.success();
    }

    private List<DeviceDataBpDto> packageBpList(String bpData) {
        if (StringUtils.isBlank(bpData)) {
            return null;
        }
        DeviceBpExternalDto deviceBpExternalDto = JSONObject.parseObject(bpData, DeviceBpExternalDto.class);
        if (null == deviceBpExternalDto) {
            return null;
        }
        List<DeviceBpDataExternalDto> dataList = deviceBpExternalDto.getData();
        if (CollectionUtils.isEmpty(dataList)) {
            return null;
        }
        List<DeviceDataBpDto> dtoList = Lists.newArrayList();
        for (DeviceBpDataExternalDto data : dataList) {
            DeviceDataBpDto dto = new DeviceDataBpDto();
            String time = data.getAddTime();
            if (StringUtils.isBlank(time)) {
                continue;
            }
            String dbp = data.getDbp();
            if (StringUtils.isBlank(dbp)) {
                continue;
            }
            String sbp = data.getSbp();
            if (StringUtils.isBlank(sbp)) {
                continue;
            }
            dto.setTime(DateUtil.getSecond(DateUtil.addDateOfField(DateUtil.parseDate(time),DateUtil.HH,-8)));
            dto.setDbp(Integer.valueOf(dbp));
            dto.setSbp(Integer.valueOf(sbp));
            dtoList.add(dto);
        }
        return dtoList;
    }

    private List<DeviceDataStepsDto> packageStepList(String stepData) {
        if (StringUtils.isBlank(stepData)) {
            return null;
        }
        DeviceStepExternalDto deviceStepExternalDto = JSONObject.parseObject(stepData, DeviceStepExternalDto.class);
        if (null == deviceStepExternalDto) {
            return null;
        }
        List<DeviceStepDataExternalDto> dataList = deviceStepExternalDto.getData();
        if (CollectionUtils.isEmpty(dataList)) {
            return null;
        }
        List<DeviceDataStepsDto> dtoList = Lists.newArrayList();
        for (DeviceStepDataExternalDto data : dataList) {
            String step = data.getStep();
            if (StringUtils.isBlank(step)) {
                continue;
            }
            String time = data.getAddTime();
            if (StringUtils.isBlank(time)) {
                continue;
            }
            DeviceDataStepsDto dto = new DeviceDataStepsDto();
            dto.setTime(DateUtil.getSecond(DateUtil.addDateOfField(DateUtil.parseDate(time),DateUtil.HH,-8)));
            dto.setStep(Integer.valueOf(step));
            dto.setState(StatusEnum.VALID.getKey());
            dtoList.add(dto);
        }
        return dtoList;
    }

    private String getDeviceData(String mac, String version, String deviceId, String bluetooth, String dataType) {
        try {
            PostMethod postMethod = new PostMethod(DEVICE_DATA_URL);
            postMethod.setRequestHeader("User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0");
            postMethod.setRequestHeader("Cache-Control", "no-cache");
            postMethod.setRequestHeader("Accept", "*/*");
            postMethod.setRequestHeader("Accept-Encoding", "gzip, deflate, br");
            postMethod.setRequestHeader("Connection", "keep-alive");
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            postMethod.setRequestHeader("Content-Length", "86");
            //postMethod.setRequestHeader("Keep-Alive", "300");
            //参数设置，需要注意的就是里边不能传NULL，要传空字符串
            NameValuePair[] data = {
                    new NameValuePair("mac", mac),
                    new NameValuePair("deviceId", deviceId),
                    new NameValuePair("version", version),
                    new NameValuePair("bluetooth", bluetooth),
                    new NameValuePair("dataType", dataType)
            };
            postMethod.setRequestBody(data);
            HttpClient httpClient = new HttpClient();
            httpClient.executeMethod(postMethod);
            return postMethod.getResponseBodyAsString();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
